YAHOO.namespace("user.card");
YAHOO.namespace("user.card.his");

Event = YAHOO.util.Event;

YAHOO.user.card.his.init = function () {

    var number_per_page_default = 20;
    var paginator = new YAHOO.widget.Paginator({
        containers: ['userCards-paging'],
        rowsPerPage: number_per_page_default,
        firstPageLinkLabel: '首页',
        previousPageLinkLabel: '上一页',
        nextPageLinkLabel: '下一页',
        lastPageLinkLabel: '末页'
    });
    var tableConfig = {
        paginator: paginator,
        MSG_EMPTY: '没有记录',
        dynamicData: true,
        initialLoad: false
    };

    var columnDefs = [
        {key: "cardId", label: '卡号'},
        {key: "cardType", label: '类型'},
        {key: "cardParValue", label: '星币值'},
        {key: "cardBalance", label: '余额'},
        {key: "cardLockedBalance", label: '锁币额度'},
        {key: "cardExpirationDate", label: '过期日期'},
        {key: "cardActivationDate", label: '激活时间'}
    ];
    var dataSource = new YAHOO.util.DataSource('/ozing/user/cards/json?');
    dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    dataSource.responseSchema = {
        resultsList: 'records',
        fields: ['cardId', 'cardType', 'cardParValue', 'cardBalance', 'cardLockedBalance', 'cardExpirationDate', 'cardActivationDate'],
        metaFields: {
            totalRecords: 'totalRecords',
            paginationRecordOffset: "startIndex",
            paginationRowsPerPage: "pageSize"
        },
        selectionMode:"single"
    };

    var dataTable = new YAHOO.widget.DataTable("userCards-table", columnDefs, dataSource, tableConfig);

    dataTable.showTableMessage(dataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

    var History = YAHOO.util.History;

    var handlePagination = function (state) {
        var newState = state.page;
        History.navigate("page", newState + "");
    };

    paginator.unsubscribe("changeRequest", dataTable.onPaginatorChangeRequest);
    paginator.subscribe("changeRequest", handlePagination, dataTable, true);

    dataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
        var meta = oResponse.meta;
        oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
        oPayload.pagination = {
            rowsPerPage: meta.paginationRowsPerPage || number_per_page_default,
            recordOffset: meta.paginationRecordOffset || 0
        };
        return true;
    };

    var generateRequest = function (page) {
        page = page || 1;
        var start_index = (page - 1) * number_per_page_default;
        return "start_index=" + start_index + "&num_per_page=" + number_per_page_default + "&timestamp=" + new Date().getTime() +
            "&cardType=" + $('#cardType').val() + "&cardId=" + $('#cardId').val() + "&cardPassword=" + $('#cardPassword').val() +
            "&startDate=" + $('#startDate').val() + "&endDate=" + $('#endDate').val();
    };

    var handleHistoryNavigation = function (page) {
        dataTable.getTbodyEl().style.display = "none";
        dataTable.showTableMessage('正在加载中，请稍候...');

        dataSource.sendRequest(generateRequest(page), {
            success: function () {
                dataTable.getTbodyEl().style.display = "";
                dataTable.hideTableMessage();
                dataTable.onDataReturnReplaceRows.apply(this, arguments);
            },
            failure: function () {
                dataTable.getTbodyEl().style.display = "";
                dataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                dataTable.onDataReturnReplaceRows.apply(this, arguments);
            },
            scope: dataTable,
            argument: {} // Pass in container for population at runtime via doBeforeLoadData
        });
    };

    var initialRequest = History.getBookmarkedState("page") || "1";

    History.register("page", initialRequest, handleHistoryNavigation);

    History.onReady(function () {
        renderPage();
    });

    var renderPage = function () {
        var currentState = History.getCurrentState("page");
        handleHistoryNavigation(currentState);
    };

    // Initialize the Browser History Manager.
    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

    // Subscribe to events for row selection
    dataTable.subscribe("rowMouseoverEvent", dataTable.onEventHighlightRow);
    dataTable.subscribe("rowMouseoutEvent", dataTable.onEventUnhighlightRow);
    dataTable.subscribe("rowClickEvent", dataTable.onEventSelectRow);


    Event.on("query_pages_btn", "click", function () {
        renderPage();
    });

    return {
        ds: dataSource,
        dt: dataTable
    };

};

Event.onDOMReady(function () {
    YAHOO.user.card.his.init();
});






